use std::{
    fs::{self, File},
    io::{Read, Write},
    path::Path,
    time::SystemTime,
};

use reqwest::{Client, Proxy};

const URL: &str = "https://raw.githubusercontent.com/helix-editor/helix/master/languages.toml";
const CACHE_PATH: &str = "./.cache/languages.toml";

async fn remote(proxy: Option<&str>) -> anyhow::Result<String> {
    let mut builder = Client::builder();
    if let Some(proxy) = proxy {
        builder = builder.proxy(Proxy::all(proxy)?);
    }
    let client = builder.build()?;
    let res = client.get(URL).send().await?;
    let text = res.text().await?;
    Ok(text)
}

fn get_duration(path: &Path) -> anyhow::Result<u64> {
    let meta = path.metadata()?;
    let ctime = meta.created()?;
    let now = SystemTime::now();
    let duration = now.duration_since(ctime)?;
    let second = duration.as_secs();
    let day = second / 60 / 60 / 24;
    Ok(day)
}

pub(crate) async fn remote_str(proxy: Option<&str>) -> anyhow::Result<String> {
    let path = Path::new(&CACHE_PATH);
    if path.exists() && get_duration(path)? < 1 {
        let mut file = File::open(path)?;
        let mut buffer = String::default();
        file.read_to_string(&mut buffer)?;
        Ok(buffer)
    } else {
        let str = remote(proxy).await?;
        let dir = path.parent().unwrap();
        fs::create_dir_all(dir)?;
        let mut file = File::create(path)?;
        file.write_all(str.as_bytes())?;
        Ok(str)
    }
}
